/* eslint-disable guard-for-in */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable max-nested-callbacks */
/* eslint-disable prefer-arrow-callback */
/* eslint-disable max-depth */
/* eslint-disable complexity */
/* eslint-disable no-case-declarations */
/* eslint-disable react/no-this-in-sfc */
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Button, Layout, Input, Popover, Modal, message, Spin, Empty, Drawer, Switch } from 'antd';
import CollapsePanel from '@/component/collapse';
import ModalContent from '@/component/modalContent';
import DrawerContent from '@/component/drawerContent';
import {
    editeValue,
    readOnlyFn,
    rowChanged,
    colChanged,
    onReadOnly,
    bindData,
} from './utils/index';
import {
    saveProject,
    changeName,
    saveTemplate,
    deleteProject,
    updateTemplate,
    getProjectsAndTemplates,
    deleteTemplate,
    getProcedure,
    getFields,
    getTables,
    getDatabases,
    getTemplateById,
    updateName,
    searchTemplate,
} from '@/service/templateManager';
import { EditOutlined, PlusOutlined } from '@ant-design/icons';
import * as GC from '@grapecity/spread-sheets';
import * as ExcelIO from '@grapecity/spread-excelio';
import '@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css';
import '@grapecity/spread-sheets-designer-resources-cn';
import { Designer } from '@grapecity/spread-sheets-designer-react';
import '@grapecity/spread-sheets-designer/styles/gc.spread.sheets.designer.min.css';
import './index.less';
import { handleBindDataByColStyles } from '@/utils/styles';
import { getTestEditLicense, getTestSpreadLicense } from '@/utils/license';

// @ts-ignore
// eslint-disable-next-line no-import-assign
GC.Spread.Sheets.Designer.LicenseKey = process.env.REACT_APP_SPREAD_SEY || getTestEditLicense();
// @ts-ignore
// eslint-disable-next-line no-import-assign
GC.Spread.Sheets.LicenseKey = ExcelIO.LicenseKey =
    process.env.REACT_APP_EDIT_KEY || getTestSpreadLicense();
GC.Spread.Common.CultureManager.culture('zh-cn');
const { Header, Sider, Content } = Layout;
const { Search } = Input;
// newSheetStyle(GC);
function TemplateManager(props: any) {
    // @ts-ignore
    const [defaultConfig] = useState(GC.Spread.Sheets.Designer.DefaultConfig);
    const [spread, setSpread] = useState<any>('');
    // 模拟模板数据
    const [templateList, setTemplateList] = useState<any>([]);
    // 模态框开关
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modalType, setModalType] = useState(1);
    const [modalTitle, setModalTitle] = useState('');
    // 流程数据
    const [procedureList, setProcedureList] = useState([
        {
            procedureId: '123',
            procedureName: '流程一',
        },
        {
            procedureId: '1233',
            procedureName: '流程二',
        },
    ]);
    // 数据库数据 选中数据库id
    const [databasesList, setDatabasesList] = useState<any>([]);
    const [databaseName, setdatabaseName] = useState<any>(null);
    // 表名
    const [tablesList, setTablesList] = useState<any>([]);
    const [tableName, settableName] = useState<any>(null);
    // 字段
    const [fieldList, setFieldList] = useState<any>([]);
    const [fieldName, setfieldName] = useState<any>(null);
    // 流程绑定
    const [process, setProcess] = useState<any>(null);
    // 项目名称
    const [projectName, setProjectName] = useState('');
    // 项目id
    const [projectId, setProjectId] = useState('');
    // 模板id
    const [templateId, setTemplateId] = useState('');
    // 模板名称
    const [templateName, setTemplateName] = useState('');
    // 模板信息
    const [templateInfo, setTemplateInfo] = useState<any>({});
    // 唯一键
    const [column, setColumn] = useState<any>('');
    // 值
    const [value, setValue] = useState<any>('');
    // 绑定的数据源
    const [bindInfo, setBindInfo] = useState<any>(null);
    // 绑定的源数据
    const [sourceData, setSourceData] = useState<any>(null);
    // 单元格只读状态
    const [readOnly, setReadOnly] = useState(false);
    const [activeChange, setActionChange] = useState(true);
    const [loadingFlag, setLoadingFlag] = useState(false);
    const [closeFlag, setCloseFlag] = useState(false);
    const panelInd = useRef<any>(null);
    const flag = useRef<any>(false);
    const [isDrawerOpen, setIsDrawerOpen] = useState(false);
    const [viewFlag, setViewFlag] = useState(true);

    const clearInput = () => {
        setdatabaseName(null);
        setfieldName(null);
        settableName(null);
        setColumn(null);
        setValue(null);
        getDatabasesList('');
    };
    const showModal = (type: number) => {
        setIsModalOpen(true);
        setModalType(type);
        switch (type) {
            case 1:
                setModalTitle('流程绑定');
                break;
            case 2:
                // @ts-ignore
                let spread = GC.Spread.Sheets.Designer.findControl('designer').getWorkbook();
                let sheet = spread.getActiveSheet();
                const selections = sheet.getSelections();
                const sheetName = sheet.name();
                // eslint-disable-next-line no-empty
                const dataObj = bindInfo?.[sheetName]?.[selections[0].row]?.[selections[0].col];
                if (dataObj?.databaseName) {
                    setdatabaseName(dataObj.databaseName);
                    setfieldName(dataObj.fieldName);
                    settableName(dataObj.tableName);
                    setColumn(dataObj.filter.column);
                    setValue(dataObj.filter.value);
                    getTableList({ name: '', databaseName: dataObj.databaseName });
                    getFieldList({
                        name: '',
                        tableName: dataObj.tableName,
                        databaseName: dataObj.databaseName,
                    });
                } else {
                    clearInput();
                }
                setModalTitle('数据绑定');
                break;
            case 3:
                setProjectName('');
                setModalTitle('项目名称');
                break;
            case 4:
                setModalTitle('新建模板');
                break;
            case 5:
                setModalTitle('项目重命名');
                break;
            case 6:
                setModalTitle('模板重命名');
                break;
            default:
                break;
        }
    };
    // 获取项目以及模板数据
    const getList = async () => {
        setLoadingFlag(true);
        const data = await getProjectsAndTemplates();
        setLoadingFlag(false);
        if (data.data.msg === 'success' && data.data.data) {
            // eslint-disable-next-line no-console
            let temId = window.location.search.split('=')[1];
            temId
                ? getTemplate(temId, data.data.data.projects)
                : setTemplateList(data.data.data.projects);
        } else {
            setTemplateList([]);
        }
    };
    // 根据模板id获取
    const getTemplate = async (id: string, lists: any) => {
        setSourceData({});
        setLoadingFlag(true);
        const data = await getTemplateById({ templateId: id });
        // console.log(data, 'datadatadatadata====>');
        setLoadingFlag(false);
        if (data.data.data) {
            const template = data.data.data;
            setTemplateInfo(template);
            setProcess(template.procedureId);
            setBindInfo(template.bindInfo ? JSON.parse(template.bindInfo) : {});
            setSourceData(template.sourceData ? JSON.parse(template.sourceData) : {});
            const list = JSON.parse(JSON.stringify(lists));
            list.forEach((item: any, ind: number) => {
                // eslint-disable-next-line max-nested-callbacks
                item.templates?.forEach((el: any) => {
                    el.isChecked = false;
                    if (id === el.templateId) {
                        if (flag.current) {
                            panelInd.current = ind;
                        }
                        flag.current = false;
                        el.isChecked = true;
                    }
                });
            });
            setTemplateList(list);
        } else {
            setTemplateList(lists);
        }
    };
    // getProcedure
    const getProcedureList = async (name: string) => {
        const data = await getProcedure({ name });
        if (data.data.msg === 'success' && data.data.data) {
            setProcedureList(data.data.data.procedures);
        }
    };
    // 获取数据库
    const getDatabasesList = async (name: string) => {
        const data = await getDatabases({ name });
        if (data.data.msg === 'success' && data.data.data) {
            setDatabasesList(data.data.data.procedures);
        }
    };
    // 获取库表
    const getTableList = async (params: any) => {
        const data = await getTables({ ...params });
        if (data.data.msg === 'success' && data.data.data) {
            setTablesList(data.data.data.tables);
        }
    };
    // 获取字段
    const getFieldList = async (params: any) => {
        const data = await getFields({ ...params });
        if (data.data.msg === 'success' && data.data.data) {
            setFieldList(data.data.data.fields);
        }
    };
    useEffect(() => {
        // @ts-ignore
        let spread = GC.Spread.Sheets.Designer.findControl('designer').getWorkbook();
        setSpread(spread);
        flag.current = true;
        getList();
        getProcedureList('');
        getDatabasesList('');
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    // 浏览器关闭提示未保存
    const beforeunload = (e: any) => {
        let confirmationMessage = '系统可能不会保存您所做的更改';
        (e || window.event).returnValue = confirmationMessage;
        return confirmationMessage;
    };
    useEffect(() => {
        if (closeFlag) {
            window.addEventListener('beforeunload', beforeunload);
            return () => {
                window.removeEventListener('beforeunload', beforeunload);
            };
        }
    }, [closeFlag]);
    // 单元格值发生改变
    const valueChanged = (bindInfo: any, info: any, blo: boolean) => {
        let bindInfos = JSON.parse(bindInfo ? JSON.stringify(bindInfo) : '{ }');
        const sheetName = info.sheetName;
        const col = info.col.toString();
        const row = info.row.toString();
        const bindJson = editeValue(bindInfos, sheetName, col, row, blo);
        setBindInfo(bindJson);
    };
    const upDataLocal = useCallback(() => {
        setTimeout(() => {
            // @ts-ignore
            let spread: any = GC.Spread.Sheets.Designer.findControl('designer').getWorkbook();
            console.log(spread.toJSON(), '=====>');
        }, 400);
        // localStorage.setItem('spread-jsons', JSON.stringify(spread.toJSON()));
    }, []);
    useEffect(() => {
        // @ts-ignore
        let spread = GC.Spread.Sheets.Designer.findControl('designer').getWorkbook();
        let activeSheet = spread.getActiveSheet();
        const selections = activeSheet.getSelections();
        readOnlyFn(bindInfo, activeSheet, selections, (flag: any) => {
            setReadOnly(flag);
        });
        // 选择区域变更事件
        activeSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, function (e: any, info: any) {
            readOnlyFn(bindInfo, activeSheet, info.newSelections, (flag: any) => {
                setReadOnly(flag);
            });
        });
        // 单元格值变更事件
        activeSheet.bind(GC.Spread.Sheets.Events.ValueChanged, function (e: any, info: any) {
            setCloseFlag(true);
            if (info.newValue) {
                valueChanged(bindInfo, info, true);
            } else {
                valueChanged(bindInfo, info, false);
            }
        });
        activeSheet.bind(GC.Spread.Sheets.Events.CellChanged, function (e: any, info: any) {
            console.log('oldvalue:' + info + '-------newvalue:' + info.newValue, e);
            console.log('=========================>activeSheetactiveSheet');
            if (viewFlag) {
                return;
            }
            const jsons = JSON.parse(localStorage.getItem('spread-jsons') || '{}');
            let _activeSheet = spread.getActiveSheet();
            let sheetName = _activeSheet.name();
            if (Object.keys(jsons).length) {
                jsons.sheets[sheetName] = _activeSheet.toJSON();
                localStorage.setItem('spread-jsons', JSON.stringify(jsons));
            }
        });
        // 选择删除表单事件
        spread.bind(GC.Spread.Sheets.Events.SheetChanging, function (e: any, info: any) {
            upDataLocal();
        });
        // sheet页切换事件
        spread.bind(GC.Spread.Sheets.Events.SheetTabClick, function (e: any, info: any) {
            // console.log('===========>', info, e);
            setActionChange(!activeChange);
            upDataLocal();
        });
        // 行变更事件
        activeSheet.bind(GC.Spread.Sheets.Events.RowChanged, function (e: any, info: any) {
            setCloseFlag(true);
            rowChanged(bindInfo, info, (binds: any) => {
                setBindInfo(binds);
                upDataLocal();
                console.log('rowChanged====>', binds);
            });
        });
        // 列变更事件
        activeSheet.bind(GC.Spread.Sheets.Events.ColumnChanged, function (e: any, info: any) {
            setCloseFlag(true);
            colChanged(bindInfo, info, (binds: any) => {
                setBindInfo(binds);
                upDataLocal();
                console.log('colChanged====>', binds);
            });
        });
        // sheet名称变更事件
        spread.bind(GC.Spread.Sheets.Events.SheetNameChanged, function (sender: any, args: any) {
            setCloseFlag(true);
            upDataLocal();
            // localStorage.setItem('sheet-styles', JSON.stringify(spread.toJSON() || {}));
        });
        return () => {
            spread.unbind(GC.Spread.Sheets.Events.SheetNameChanged);
            spread.unbind(GC.Spread.Sheets.Events.RowChanged);
            spread.unbind(GC.Spread.Sheets.Events.ColumnChanged);
            spread.unbind(GC.Spread.Sheets.Events.SheetTabClick);
            spread.unbind(GC.Spread.Sheets.Events.ValueChanged);
            spread.unbind(GC.Spread.Sheets.Events.SelectionChanged);
            spread.unbind(GC.Spread.Sheets.Events.CellChanged);
            // spread.unbind(GC.Spread.Sheets.Events.SheetChanged);
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [bindInfo, activeChange]);
    const handleOk = async () => {
        switch (modalType) {
            case 2:
                if (templateInfo.templateId) {
                    if (!databaseName || !tableName || !fieldName) {
                        message.warning('数据库，数据表，字段其中不能为空');
                        return;
                    } else {
                        setCloseFlag(true);
                        let spread = // @ts-ignore
                            GC.Spread.Sheets.Designer.findControl('designer').getWorkbook();
                        let sheet = spread.getActiveSheet();
                        bindData(
                            sheet,
                            bindInfo,
                            tableName,
                            databaseName,
                            fieldName,
                            column,
                            value,
                            (binds: any) => {
                                setBindInfo(binds);
                            }
                        );
                        setReadOnly(true);
                    }
                } else {
                    message.warning('请选择模板');
                    return;
                }

                break;
            case 3:
                if (projectName) {
                    setLoadingFlag(true);
                    const data = await saveProject({ name: projectName });
                    setLoadingFlag(false);
                    if (data.data.msg === 'success') {
                        message.success('新建项目成功');
                        getList();
                        setProjectName('');
                    } else {
                        message.error(data.data.msg);
                        return;
                    }
                } else {
                    message.warning('项目名称不能为空');
                    return;
                }
                break;
            case 4:
                if (templateName) {
                    setLoadingFlag(true);
                    const data = await saveTemplate({ name: templateName, projectId });
                    setLoadingFlag(false);
                    if (data.data.msg === 'success') {
                        message.success('新建模板成功');
                        getList();
                        setTemplateName('');
                    } else {
                        message.error(data.data.msg);
                        return;
                    }
                } else {
                    message.warning('模板名称不能为空');
                    return;
                }
                break;
            case 5:
                if (projectName) {
                    setLoadingFlag(true);
                    const data = await changeName({ name: projectName, projectId });
                    setLoadingFlag(false);
                    if (data.data.msg === 'success') {
                        message.success('修改项目名称成功');
                        getList();
                        setProjectName('');
                    } else {
                        message.error(data.data.msg);
                        return;
                    }
                } else {
                    message.warning('项目名称不能为空');
                    return;
                }
                break;
            case 6:
                if (templateName) {
                    setLoadingFlag(true);
                    const data = await updateName({
                        name: templateName,
                        templateId,
                    });
                    setLoadingFlag(false);
                    if (data.data.msg === 'success') {
                        message.success('修改模板名称成功');
                        getList();
                        setTemplateName('');
                    } else {
                        message.error(data.data.msg);
                        return;
                    }
                } else {
                    message.warning('模板名称不能为空');
                    return;
                }
                break;
            default:
                break;
        }
        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    // 报告模板编辑
    const onReportTemplate = () => {
        if (templateInfo.templateId) {
            showModal(6);
            setTemplateName(templateInfo.name);
            setTemplateId(templateInfo.templateId);
        } else {
            message.warning('请选择模板');
        }
    };
    // 搜索报告模板
    const onSearchTemplate = async (value: string) => {
        if (value) {
            setLoadingFlag(true);
            const data = await searchTemplate({ name: value });
            setLoadingFlag(false);
            if (data.data.data) {
                setTemplateList(data.data.data.projects);
                setTemplateInfo({});
            } else {
                setTemplateList([]);
                setTemplateInfo({});
            }
        } else {
            getList();
        }
    };
    // 模板变更回显表样以及当前单元格是否可读
    useEffect(() => {
        // @ts-ignore
        let spread = GC.Spread.Sheets.Designer.findControl('designer').getWorkbook();
        spread.suspendPaint();
        spread.fromJSON(JSON.parse(templateInfo.sheetInfo ? templateInfo.sheetInfo : '{ }'));
        spread.resumePaint();
        let sheet = spread.getActiveSheet();
        const selections = sheet.getSelections();
        readOnlyFn(templateInfo.bindInfo, sheet, selections, (flag: any) => {
            setReadOnly(flag);
        });
    }, [templateInfo]);
    // 项目名称以及模板列表操作项
    const templateAction = (item: any, el: any, isChild: boolean) => {
        if (isChild) {
            setTemplateId(item.templateId);
            switch (el.label) {
                case '重命名':
                    setTemplateName(item.name);
                    showModal(6);
                    break;
                case '删除模板':
                    break;
                default:
                    break;
            }
        } else {
            setProjectId(item.projectId);
            switch (el.label) {
                case '新建模板':
                    setTemplateName('');
                    showModal(4);
                    break;
                case '重命名':
                    setProjectName(item.projectName);
                    showModal(5);
                    break;
                case '删除项目':
                    break;
                default:
                    break;
            }
        }
    };
    const confirm = async (isChild: any) => {
        if (isChild) {
            setLoadingFlag(true);
            const data = await deleteTemplate({ templateId });
            setLoadingFlag(false);
            let temId = window.location.search.split('=')[1];
            if (data.data.msg === 'success') {
                if (templateInfo.templateId === templateId) {
                    setTemplateInfo({});
                }
                if (templateInfo.templateId === temId) {
                    window.history.pushState(null, '', '');
                }
                message.success('删除模板成功');
                getList();
            } else {
                message.error(data.data.msg);
                return;
            }
        } else {
            setLoadingFlag(true);
            const data = await deleteProject({ projectId });
            setLoadingFlag(false);
            if (data.data.msg === 'success') {
                if (templateInfo.projectId === projectId) {
                    setTemplateInfo({});
                }
                message.success('删除项目成功');
                getList();
            } else {
                message.error(data.data.msg);
                return;
            }
        }
    };
    // 流程绑定事件
    const handleProcess = (value: string) => {
        setProcess(value);
    };
    // 数据库下拉事件
    const handleDatabase = async (value: string) => {
        setdatabaseName(value);
        getDatabasesList('');
        const data = await getTables({ name: '', databaseName: value });
        if (data.data.msg === 'success') {
            setTablesList(data.data.data.tables);
        }
        settableName(null);
        setfieldName(null);
    };
    // 表名下拉事件
    const handleTable = async (value: string) => {
        getTableList({ name: '', databaseName });
        const data = await getFields({ name: '', tableName: value, databaseName });
        if (data.data.msg === 'success') {
            setFieldList(data.data.data.fields);
        }
        settableName(value);
        setfieldName(null);
    };
    // 字段下拉事件
    const handleField = (value: string) => {
        setfieldName(value);
        getFieldList({ name: '', tableName, databaseName });
    };
    const onSearch = (value: string, type: number) => {
        switch (type) {
            case 1:
                getProcedureList(value);
                break;
            case 2:
                getDatabasesList(value);
                break;
            case 3:
                getTableList({ name: value, databaseName });
                break;
            case 4:
                getFieldList({
                    name: '',
                    tableName,
                    databaseName,
                });
                break;
            default:
                break;
        }
    };
    // 保存模板
    const saveSheet = async () => {
        // @ts-ignore
        let spread = GC.Spread.Sheets.Designer.findControl('designer').getWorkbook();
        console.log(spread, 'asdadadasdasdasdad');
        const jsons = spread.toJSON();
        console.log(jsons, 'jsonsjsonsjsonsjsonsjsons');
        if (templateInfo.templateId) {
            setLoadingFlag(true);
            const data = await updateTemplate({
                templateId: templateInfo.templateId,
                sheetInfo: JSON.stringify(jsons),
                bindInfo: JSON.stringify(bindInfo),
                sourceData: JSON.stringify(sourceData),
                procedureId: process,
                templateVersionId: templateInfo.templateVersionId
                    ? templateInfo.templateVersionId
                    : null,
                version: templateInfo.version,
            });
            setLoadingFlag(false);
            if (data.data.msg === 'success') {
                setCloseFlag(false);
                message.success('保存成功');
                getList();
                let sheet = spread.getActiveSheet();
                const sheetName = sheet.name();
                spread.suspendPaint();
                sheet.resumeCalcService(false);
                // handleBindDataByColStyles(GC, spread, sheetName, bindInfo, true, false);
                spread.resumePaint();
                sheet.resumeCalcService(true);
            } else {
                message.error(data.data.msg);
                return;
            }
        } else {
            message.warning('请选择模板');
        }
    };
    // 设置只读 取消只读
    const handleReadOnly = () => {
        if (templateInfo.templateId) {
            setCloseFlag(true);
            // @ts-ignore
            let spread = GC.Spread.Sheets.Designer.findControl('designer').getWorkbook();
            let sheet = spread.getActiveSheet();
            const selections = sheet.getSelections();
            const sheetName = sheet.name();
            onReadOnly(bindInfo, sheetName, selections, readOnly, (binds: any) => {
                console.log(binds, 'bindsbindsbindsbindsbinds');
                setBindInfo(binds);
            });
        } else {
            message.warning('请选择模板');
        }
    };

    const showDrawer = () => {
        if (templateInfo.templateId) {
            setIsDrawerOpen(true);
        } else {
            message.warning('请先选择模板');
        }
    };

    const onCloseDrawer = () => {
        setIsDrawerOpen(false);
    };
    const onViewChange = (checked: boolean) => {
        setViewFlag(checked);
    };
    useEffect(() => {
        if (
            !templateInfo ||
            (typeof templateInfo === 'object' && !Object.keys(templateInfo).length)
        ) {
            return;
        }
        localStorage.setItem('spread-jsons', templateInfo.sheetInfo);
    }, [templateInfo]);
    // 设置预览数据
    useEffect(() => {
        if (!spread) {
            return;
        }
        let sheet = spread.getActiveSheet();
        const sheetName = sheet.name();
        const _sourceData = sourceData[sheetName] || {};
        spread.suspendPaint();
        sheet.resumeCalcService(false);
        const bindData = bindInfo ? bindInfo[sheetName] : {};
        if (!bindData) {
            for (let row in _sourceData) {
                for (let col in _sourceData[row]) {
                    const { tableName, fieldName, dataType }: any = _sourceData[row][col];
                    let val = viewFlag ? `${tableName}.${fieldName}.${dataType}` : '';
                    // tableInfo[row][col].value = val;
                    // console.log(val, 'asdasdadadasd');
                    sheet.setValue(row, col, val);
                }
            }
        }
        let spreadAll: any = JSON.parse(localStorage.getItem('spread-jsons') || '{}');
        console.log(spreadAll, '=====>');
        let sheetInfo = spreadAll?.sheets ? spreadAll?.sheets[sheetName] : undefined;
        if (!sheetInfo) {
            spread.resumePaint();
            sheet.resumeCalcService(true);
            sheet.options.isProtected = viewFlag;
            return;
        }
        let currentSheetInfo: any = sheetInfo || { data: {} };
        if (!currentSheetInfo) {
            currentSheetInfo = {
                data: {
                    dataTable: {},
                },
            };
        } else if (currentSheetInfo?.data && !currentSheetInfo?.data?.dataTable) {
            currentSheetInfo.data.dataTable = {};
        } else if (!currentSheetInfo?.data) {
            currentSheetInfo.data = {
                dataTable: {},
            };
        }
        let tableInfo = currentSheetInfo?.data.dataTable;
        if (viewFlag && templateInfo) {
            for (let row in bindData) {
                if (!tableInfo[row]) {
                    tableInfo[row] = {};
                }
                for (let col in bindData[row]) {
                    if (!tableInfo[row][col] || !tableInfo[row][col].style) {
                        tableInfo[row][col] = {
                            style: {},
                            value: '',
                        };
                    }
                    // eslint-disable-next-line @typescript-eslint/prefer-optional-chain
                    if (_sourceData[row] && _sourceData[row][col]) {
                        const { tableName, fieldName, dataType }: any = _sourceData[row][col];
                        let val = viewFlag ? `${tableName}.${fieldName}.${dataType}` : '';
                        tableInfo[row][col].value = val;
                    }
                    let styes = tableInfo[row][col].style;
                    styes.backColor = 'rgba(241, 241, 241, 1)';
                    if (!styes.borderTop) {
                        styes.borderTop = { style: 1, color: '#DCDCDC', level: 10 };
                    }
                    if (!styes.borderRight) {
                        styes.borderRight = { style: 1, color: '#DCDCDC', level: 10 };
                    }
                    if (!styes.borderButtom) {
                        styes.borderButtom = { style: 1, color: '#DCDCDC', level: 10 };
                    }
                    if (!styes.borderLeft) {
                        styes.borderLeft = { style: 1, color: '#DCDCDC', level: 10 };
                    }
                    // // eslint-disable-next-line no-debugger
                    // // debugger;
                    // console.log(tableInfo, 'tableInfotableInfotableInfotableInfo');
                }
            }
        }
        console.log(currentSheetInfo, 'currentSheetInfocurrentSheetInfo', tableInfo, bindData);
        tableInfo && sheet.fromJSON(currentSheetInfo || {});
        spread.resumePaint();
        sheet.resumeCalcService(true);
        sheet.options.isProtected = viewFlag;
    }, [sourceData, viewFlag, bindInfo, templateInfo]);
    return (
        <div className="template-manager-container" style={{ height: '100%' }}>
            <Layout className="base-layout">
                <Sider
                    trigger={null}
                    style={{
                        backgroundColor: '#ffffff',
                        padding: '20px 20px',
                        borderRight: '1px solid #ccc',
                    }}
                    width={280}
                >
                    <div className="report_list">
                        <span>项目管理</span>
                        <Popover
                            placement="right"
                            content={
                                <p className="action_list" onClick={() => showModal(3)}>
                                    新建项目
                                </p>
                            }
                            trigger="click"
                        >
                            <PlusOutlined
                                style={{
                                    fontSize: '18px',
                                    color: '#00AF6F',
                                    cursor: 'pointer',
                                }}
                            />
                        </Popover>
                    </div>
                    <Search
                        placeholder="搜索模板名称"
                        onSearch={onSearchTemplate}
                        style={{ width: '100%' }}
                    />
                    <div className="template_list">
                        <CollapsePanel
                            defaultActiveKey={panelInd.current}
                            templateList={templateList}
                            templateAction={templateAction}
                            confirm={confirm}
                            getTemplate={getTemplate}
                        />
                    </div>
                </Sider>
                <Layout className="site-layout">
                    <Header className="site-layout-background-header" style={{ padding: '0 20px' }}>
                        <div className="template_modal">
                            <span
                                className="report_template"
                                title={templateInfo ? templateInfo.name : null}
                            >
                                {templateInfo ? templateInfo.name : null}
                            </span>
                            {templateInfo.templateId && (
                                <EditOutlined
                                    style={{
                                        fontSize: '16px',
                                        color: '#00AF6F',
                                        cursor: 'pointer',
                                    }}
                                    onClick={onReportTemplate}
                                />
                            )}
                        </div>
                        <div className="action_btn">
                            <span className="viewFlag">
                                <span>设置预览</span>
                                <Switch checked={viewFlag} onChange={onViewChange} />
                            </span>
                            <Button onClick={showDrawer}>数据源设置</Button>
                            <Button onClick={() => showModal(1)}>流程绑定</Button>
                            <Button onClick={() => showModal(2)}>数据绑定</Button>
                            <Button onClick={handleReadOnly}>
                                {readOnly ? '取消只读' : '设置只读'}
                            </Button>
                            <Button
                                type="primary"
                                onClick={() => saveSheet()}
                                disabled={viewFlag ? true : false}
                            >
                                保存
                            </Button>
                        </div>
                    </Header>
                    <Content
                        className="site-layout-background"
                        style={{
                            minHeight: 280,
                        }}
                    >
                        <Designer
                            styleInfo={{
                                width: '100%',
                                height: '100%',
                                display: `${templateInfo.templateId ? 'block' : 'none'}`,
                            }}
                            config={defaultConfig}
                            spreadOptions={{ sheetCount: 2 }}
                        />
                        {!templateInfo.templateId && <Empty description="请选择模板" />}
                    </Content>
                </Layout>
            </Layout>
            <Modal title={modalTitle} visible={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <ModalContent
                    modalType={modalType}
                    handleProcess={handleProcess}
                    process={process}
                    onSearch={onSearch}
                    getProcedureList={getProcedureList}
                    procedureList={procedureList}
                    databaseName={databaseName}
                    getDatabasesList={getDatabasesList}
                    handleDatabase={handleDatabase}
                    databasesList={databasesList}
                    tableName={tableName}
                    getTableList={getTableList}
                    handleTable={handleTable}
                    tablesList={tablesList}
                    fieldName={fieldName}
                    getFieldList={getFieldList}
                    handleField={handleField}
                    fieldList={fieldList}
                    column={column}
                    setColumnFn={(e: string) => {
                        setColumn(e);
                    }}
                    value={value}
                    setValueFn={(e: string) => {
                        setValue(e);
                    }}
                    projectName={projectName}
                    setProjectNameFn={(e: string) => {
                        setProjectName(e);
                    }}
                    templateName={templateName}
                    setTemplateNameFn={(e: string) => {
                        setTemplateName(e);
                    }}
                />
            </Modal>
            <Drawer
                title="数据源设置"
                placement="right"
                onClose={onCloseDrawer}
                visible={isDrawerOpen}
                closable={false}
            >
                {
                    // eslint-disable-next-line react/self-closing-comp
                    <DrawerContent
                        isDrawerOpen={isDrawerOpen}
                        spread={spread}
                        sourceData={sourceData}
                        setSourceDataFn={(e: any) => {
                            setSourceData(e);
                        }}
                        setisDrawerOpenFn={() => {
                            setIsDrawerOpen(false);
                        }}
                    ></DrawerContent>
                }
            </Drawer>
            {loadingFlag && (
                <div className="loadding">
                    <Spin size="large" />
                </div>
            )}
        </div>
    );
}

export default TemplateManager;
